package com.geek.novel.activity.book

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.TextView
import com.geek.novel.R
import com.geek.novel.activity.base.TitleBarActivity
import com.geek.novel.bo.AppContext
import com.geek.novel.common.Constant
import com.geek.novel.entity.BookCrawler
import com.geek.novel.entity.BookRead
import com.geek.novel.entity.CrawlerSource
import com.geek.novel.network.RslHandler
import com.geek.novel.services.BookCrawlerRepository
import com.geek.novel.services.BookRepository
import com.geek.novel.services.CrawlerRepository
import com.geek.novel.services.NovelService
import com.geek.novel.utils.FormatUtil
import com.geek.novel.utils.ToastUtils
import com.geek.novel.vo.ApiErrorResult
import com.geek.novel.vo.ApiResult
import kotlinx.android.synthetic.main.activity_crawler_source.*


/**
 * 书籍换源选择页面
 */
class CrawlerSourceActivity: TitleBarActivity(), RslHandler {

	override fun pageName(): String{
		return AppContext.getContext().getString(R.string.title_bar_page_crawler_source)
	}

	/**列表数据*/
	private val list = arrayListOf<BookCrawler>()

	/**列表的适配器*/
	private lateinit var listViewAdapter: ListAdapter
	
	/**小说服务*/
	private lateinit var novelService: NovelService
	
	private var bookId: String? = null
	private lateinit var book: BookRead
	
	/**书籍的数据库类*/
	private var bookRepository = BookRepository.getInstance()
	
	/**爬虫源的数据库类*/
	private var crawlerRepository = CrawlerRepository.getInstance()
	
	/**书本源的数据库类*/
	private var bookCrawlerRepository = BookCrawlerRepository()

	/**默认的爬虫源*/
	private var activieCrawlerSource: CrawlerSource? = null

	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		setContentView(R.layout.activity_crawler_source)
		
		//获取bookId
		val bundle = intent.extras?:Bundle()
		this.bookId = bundle.getString("bookId")
		if(TextUtils.isEmpty(this.bookId)){
			ToastUtils.toast("入参书籍id不能为空！")
			finish()
			return
		}
		this.book = bookRepository.findBookByBookId(bookId)!!
		
		novelService = NovelService(this)
		novelService.getBookCrawlerList(bookId!!)

		//初始化列表
		val list = bookCrawlerRepository.findByBookId(this.bookId!!)
		this.initListData(list)

		//获取默认的爬虫源
		this.activieCrawlerSource = crawlerRepository.findByActive()
	}

	/**初始化列表*/
	private fun initListData(list: List<BookCrawler>){
		this.list.clear()
		this.list.addAll(list)
	}

	/**附加控件*/
	override fun attachViewChild() {
		listViewAdapter = ListAdapter(this, list)
		lv_crawler_source_list.adapter = listViewAdapter
	}

	override fun clickEvent(id: Int, v: View) {
	}

	/**列表项的适配器*/
	inner class ListAdapter(context: Context, private val list: List<BookCrawler>)
		: ArrayAdapter<BookCrawler>(context, R.layout.listview_crawler_source, list) {
		@SuppressLint("ViewHolder", "SetTextI18n")
		override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
			var view = convertView
			if(view == null){
				view = LayoutInflater.from(context).inflate(R.layout.listview_crawler_source, null)
			}
			val entity = list[position]

			//判断是否是默认爬虫源
			val active = if(activieCrawlerSource != null){
				list.find { it.crawlSourceId == "${activieCrawlerSource!!.id}" }
			}else{
				null
			}
			
			val crawlerSource = crawlerRepository.getById(entity.crawlSourceId)
			
			if(crawlerSource != null){
				//字体名称
				setViewText(view!!, R.id.tv_crawler_source_name, crawlerSource.name)
				
				//选择按钮
				val selectBtn = view.findViewById<TextView>(R.id.tv_select_crawler_source)
				
				val bookCrawlerId = book.bookCrawlerId
				
				//书本没有默认爬虫源的情况，选择第1个爬虫源
				if(FormatUtil.isEmpty(bookCrawlerId) && active == null && position == 0){
					selectBtn.visibility = View.GONE
				}else if(FormatUtil.isEmpty(bookCrawlerId) && crawlerSource.active == true){
					selectBtn.visibility = View.GONE
				}else if(bookCrawlerId == entity.id){
					selectBtn.visibility = View.GONE
				}else{
					selectBtn.visibility = View.VISIBLE
					selectBtn.setOnClickListener{
						entity.lastCrawlerTime = null
						bookCrawlerRepository.save(entity)

						book.bookCrawlerId = entity.id
						bookRepository.save(book)
						listViewAdapter.notifyDataSetChanged()
					}
				}
				
			}
			return view!!
		}
	}


	private fun setViewText(view: View, id: Int, text: String?){
		view.findViewById<TextView>(id).text = text
	}

	override fun onError(code: Int, err: ApiErrorResult) {
	}

	override fun onSuccess(result: ApiResult, code: Int) {
		when(code){
			//获取列表
			Constant.HTTP_KEY_APP_GET_BOOK_CRAWLER_LIST->{
				val list = result.getList(BookCrawler::class.java)
				val localList = bookCrawlerRepository.findByBookId(this.bookId!!)
				for (bookCrawler in list) {
					val localData = localList.find { item-> item.id == bookCrawler.id }
					if(localData != null){
						bookCrawler.lastIndexId = localData.lastIndexId
						bookCrawler.lastIndexName = localData.lastIndexName
						bookCrawler.lastCrawlerTime = localData.lastCrawlerTime
					}
				}
				bookCrawlerRepository.saveAll(list)
				//刷新数据
				this.initListData(list)
				listViewAdapter.notifyDataSetChanged()
			}
		}
	}

}